package com.xxq.semester.controller.utils;

import com.xxq.semester.service.impl.utils.OSSServiceImpl;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import com.xxq.semester.entity.utils.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/file")
@Tag(name= "文件管理", description = "提供文件上传、删除和检查功能")
public class FileController {

    @Autowired
    private OSSServiceImpl ossService;

    /**
     * 上传单个文件
     */
    @Operation(summary = "上传单个文件", description = "上传文件到OSS存储")
    @PostMapping("/upload")
    public ResponseEntity<Map<String, Object>> uploadFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "folder", required = false) String folder) {

        Map<String, Object> result = new HashMap<>();

        try {
            if (file.isEmpty()) {
                result.put("success", false);
                result.put("message", "文件不能为空");
                return ResponseEntity.error("文件不能为空");
            }

            String fileUrl = ossService.uploadFile(file, folder);

            result.put("success", true);
            result.put("message", "上传成功");
            result.put("fileUrl", fileUrl);
            result.put("fileName", file.getOriginalFilename());

            return ResponseEntity.success(result);

        } catch (IOException e) {
            return ResponseEntity.error("上传失败: " + e.getMessage());
        }
    }

    /**
     * 上传多个文件
     */
    @Operation(summary = "批量上传文件", description = "批量上传多个文件到OSS存储")
    @PostMapping("/upload/multiple")
    public ResponseEntity<Map<String, Object>> uploadMultipleFiles(
            @RequestParam("files") MultipartFile[] files,
            @RequestParam(value = "folder", required = false) String folder) {

        Map<String, Object> result = new HashMap<>();

        try {
            if (files.length == 0) {
                return ResponseEntity.error("请选择要上传的文件");
            }

            for (MultipartFile file : files) {
                if (file.isEmpty()) {
                    continue;
                }
                ossService.uploadFile(file, folder);
            }

            result.put("success", true);
            result.put("message", "批量上传成功");
            result.put("uploadCount", files.length);

            return ResponseEntity.success(result);

        } catch (IOException e) {
            return ResponseEntity.error("批量上传失败: " + e.getMessage());
        }
    }

    /**
     * 删除文件
     */
    @Operation(summary = "删除文件", description = "从OSS存储中删除指定文件")
    @DeleteMapping("/delete")
    public ResponseEntity<Map<String, Object>> deleteFile(@RequestParam("objectKey") String objectKey) {
        Map<String, Object> result = new HashMap<>();

        try {
            if (!ossService.doesObjectExist(objectKey)) {
                result.put("success", false);
                result.put("message", "文件不存在");
                return ResponseEntity.notfound("文件不存在");
            }

            ossService.deleteFile(objectKey);

            result.put("success", true);
            result.put("message", "删除成功");

            return ResponseEntity.success(result);

        } catch (Exception e) {
            return ResponseEntity.error("删除失败: " + e.getMessage());
        }
    }

    /**
     * 检查文件是否存在
     */
    @Operation(summary = "检查文件是否存在", description = "检查指定文件在OSS存储中是否存在")
    @GetMapping("/exists")
    public ResponseEntity<Map<String, Object>> checkFileExists(@RequestParam("objectKey") String objectKey) {
        Map<String, Object> result = new HashMap<>();

        boolean exists = ossService.doesObjectExist(objectKey);

        result.put("exists", exists);
        result.put("objectKey", objectKey);
        return ResponseEntity.success(result);
    }
    @Operation(summary = "上传文件（通过URL）", description = "通过文件URL下载并上传到OSS")
    @PostMapping("/upload/by-url")
    public ResponseEntity<Map<String, Object>> uploadByUrl(
            @RequestParam("fileUrl") String fileUrl,
            @RequestParam(value = "folder", required = false) String folder) {

        Map<String, Object> result = new HashMap<>();

        try {
            // URL解码，处理被编码的URL参数
            String decodedFileUrl = URLDecoder.decode(fileUrl, StandardCharsets.UTF_8);
            
            // 调用 OSSServiceImpl 中的封装方法
            String fileUrlOnOss = ossService.uploadFileByUrl(decodedFileUrl, folder);

            result.put("success", true);
            result.put("message", "上传成功");
            result.put("fileUrl", fileUrlOnOss);
            result.put("originalUrl", decodedFileUrl);
            return ResponseEntity.success(result);

        } catch (Exception e) {
            return ResponseEntity.error("上传失败: " + e.getMessage());
        }
    }
    @Operation(summary = "上传文件（通过URL - 使用POST body）", description = "通过POST body传递文件URL，避免URL参数问题")
    @PostMapping("/upload/by-url-body")
    public ResponseEntity<Map<String, Object>> uploadByUrlBody(
            @RequestBody Map<String, String> requestBody) {

        Map<String, Object> result = new HashMap<>();

        try {
            String fileUrl = requestBody.get("fileUrl");
            String folder = requestBody.get("folder");
            
            if (fileUrl == null || fileUrl.isBlank()) {
                return ResponseEntity.error("fileUrl不能为空");
            }
            
            // 直接使用原始URL，不需要解码
            String fileUrlOnOss = ossService.uploadFileByUrl(fileUrl, folder);

            result.put("success", true);
            result.put("message", "上传成功");
            result.put("fileUrl", fileUrlOnOss);
            result.put("originalUrl", fileUrl);
            return ResponseEntity.success(result);

        } catch (Exception e) {
            return ResponseEntity.error("上传失败: " + e.getMessage());
        }
    }
}